#include "pch.h"

#include <robuffer.h>

#include "MjpegCamera.h"

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Storage::Streams;
using namespace MjpegProcessor;

MjpegCamera::MjpegCamera(BasicLoader^ loader)
{
	m_loader = loader;
}

void MjpegCamera::Start(Uri^ uriLeft, Uri^ uriRight)
{
	if(uriLeft != nullptr)
	{
		m_decoderLeft = ref new MjpegDecoder();
		m_decoderLeft->ParseStream(uriLeft, false);
	}

	if(uriRight != nullptr)
	{
		m_decoderRight = ref new MjpegDecoder();
		m_decoderRight->ParseStream(uriRight, false);
	}
}

void MjpegCamera::Stop()
{
	m_decoderLeft->StopStream();
	m_decoderRight->StopStream();
}

void MjpegCamera::UpdateTexture(IBuffer^ buffer, Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> *texture)
{
	if(buffer != nullptr)
	{
		byte* bytes = nullptr;
		IUnknown* pUnknown = reinterpret_cast<IUnknown *>(buffer);
		IBufferByteAccess* buff = nullptr;
		pUnknown->QueryInterface(IID_PPV_ARGS(&buff));
		pUnknown->Release();
		buff->Buffer(&bytes);
		if(m_loader != nullptr)
			m_loader->CreateTexture(false, bytes, buffer->Length, nullptr, texture->GetAddressOf(), "mjpeg");
		buff->Release();
	}
}

void MjpegCamera::Update(GameEngine^ engine)
{
	if(m_decoderLeft != nullptr)
		UpdateTexture(m_decoderLeft->CurrentFrame, &textureLeft);

	if(m_decoderRight != nullptr)
		UpdateTexture(m_decoderRight->CurrentFrame, &textureRight);

	Face::Update(engine);
}

void MjpegCamera::Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer, _In_ bool isFirstPass)
{
	throw Exception::CreateException(E_FAIL, L"Wrong render called on MJPEG camera!");
}

void MjpegCamera::Render(_In_ ID3D11DeviceContext *context, _In_ ID3D11Buffer *primitiveConstantBuffer, _In_ bool isFirstPass, int eye)
{
	if(eye == 1 && textureRight != nullptr)
		m_material->SetTexture(textureRight.Get());
	else if(textureLeft != nullptr)
		m_material->SetTexture(textureLeft.Get());

	GameObject::Render(context, primitiveConstantBuffer, isFirstPass);
}